package com.treeman.api.controller.marker;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.treeman.api.ApiRequestError;
import com.treeman.api.ApiRequestError.ApiError;
import com.treeman.api.json.marker.MarkerJson;
import com.treeman.marker.exception.MarkerNotFoundException;
import com.treeman.marker.exception.NoMarkersFoundException;
import com.treeman.marker.service.MarkerService;

@Controller
@RequestMapping(value = "/api")
public class MarkerDataController {

	private static Logger log = Logger.getLogger(MarkerDataController.class);

	@Autowired
	private MarkerService markerService;

	@RequestMapping(value = "/markers/{id}", method = RequestMethod.GET)
	public @ResponseBody
	MarkerJson getMarkerById(@PathVariable Long id)
			throws MarkerNotFoundException {
		return markerService.getMarkerJsonById(id);
	}

	@RequestMapping(value = "/users/{username}/markers", method = RequestMethod.GET)
	public @ResponseBody
	List<MarkerJson> getUserMarkers(@PathVariable String username)
			throws NoMarkersFoundException {
		log.debug("Mapping: /users/" + username + "/markers");

		List<MarkerJson> markers = markerService.getUserMarkersJson(username);
		return markers;
	}

	/* EXCEPTIONS */

	@ExceptionHandler(NoMarkersFoundException.class)
	@ResponseStatus(value = HttpStatus.NOT_FOUND)
	public @ResponseBody
	ApiRequestError handleNoMarkersFoundException(NoMarkersFoundException e) {
		log.warn("There is no markers for user: " + e.getAuthor());

		return new ApiRequestError(ApiError.NOT_FOUND,
				"User doesn not have any markers.");
	}

	@ExceptionHandler(MarkerNotFoundException.class)
	@ResponseStatus(value = HttpStatus.NOT_FOUND)
	public @ResponseBody
	ApiRequestError handleMarkerNotFoundException(MarkerNotFoundException e) {
		log.warn("No marker with id: " + e.getMarkerId());

		return new ApiRequestError(ApiError.NOT_FOUND,
				"No marker with specified id.");
	}

}
